{
 "metadata": {
  "signature": "sha256:4a36b7fec82a29db52c39b33c2f6e3701d671fcb5ab51579e64e7687d63274a4"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Matplotlib: latex examples\n",
      "======================================================================\n",
      "\n",
      "Producing Graphs for Publication using LaTeX\n",
      "--------------------------------------------\n",
      "\n",
      "This page describes several ways to produce publication quality graphics\n",
      "with LaTeX.\n",
      "\n",
      "### LaTeX UsingTex\n",
      "\n",
      "This section describes a technique following the\n",
      "[\"Cookbook/Matplotlib/UsingTex\"] guidelines.\n",
      "\n",
      "Here is the outline of the LaTeX file used to include the figure\n",
      "(example for \\`REVTeX4\\` for publication is APS physics journals with a\n",
      "two column format.)"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "\\documentclass[prl,10pt,twocolumn]{revtex4}\n",
      "\\usepackage{graphicx}    % Used to import the graphics\n",
      "\\begin{document}\n",
      "%...\n",
      "\\begin{figure}[t]\n",
      "  \\begin{center}\n",
      "    \\showthe\\columnwidth % Use this to determine the width of the figure.\n",
      "    \\includegraphics[width=\\columnwidth]{fig1.eps}\n",
      "    \\caption{\\label{fig:sin_cos} Plot of the sine and cosine functions.}\n",
      "  \\end{center}\n",
      "\\end{figure}\n",
      "%...\n",
      "\\end{document}"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Determining the Figure Size\n",
      "\n",
      "The first step is to determine the size of the figure: this way, when\n",
      "the graphic is included, it will not be resized, and the fonts etc. will\n",
      "be exactly as you set them rather than scaled (and possibly distored).\n",
      "This can be done in LaTeX by explicitly setting the width of the figure\n",
      "and using the \\`\\\\showthe\\` command to print this width. (In the example\n",
      "above, the figure width is set to the \\`\\\\columnwidth\\`.)\n",
      "\n",
      "When the file is processed by LaTeX, look at the output. The example\n",
      "above produces the following output (Note: LaTeX will pause after the\n",
      "\\`\\\\showthe\\` command, press enter to continue):"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "This is TeX, Version 3.14159 (Web2C 7.4.5)\n",
      "LaTeX2e <2001/06/01>\n",
      "...\n",
      "> 246.0pt.\n",
      "l.8     \\showthe\\columnwidth\n",
      "                             % Use this to determine the width of the figure.\n",
      "?\n",
      "<fig1.eps> [1] (./tst.aux) )\n",
      "..."
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Thus, the figure will be 246.0pt wide. There are 1 inch = 72.27pt (in\n",
      "[La]TeX), so this means that the figure width should be 3.40390 inches.\n",
      "The heigth depends on the content of the figure, but the golden mean may\n",
      "be used to make a pleasing figure. Once this is determined, the\n",
      "\\`figure.figsize\\` property can be used to set the default figure size."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "#!python numbers=disable\n",
      "fig_width_pt = 246.0  # Get this from LaTeX using \\showthe\\columnwidth\n",
      "inches_per_pt = 1.0/72.27               # Convert pt to inches\n",
      "golden_mean = (sqrt(5)-1.0)/2.0         # Aesthetic ratio\n",
      "fig_width = fig_width_pt*inches_per_pt  # width in inches\n",
      "fig_height =fig_width*golden_mean       # height in inches\n",
      "fig_size = [fig_width,fig_height]"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Setting Font Sizes\n",
      "\n",
      "Since the figure will not be scaled down, we may explicitly set the font\n",
      "sizes."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "#!python numbers=disable\n",
      "          'font.size' : 10,\n",
      "          'axes.labelsize' : 10,\n",
      "          'font.size' : 10,\n",
      "          'text.fontsize' : 10,\n",
      "          'legend.fontsize': 10,\n",
      "          'xtick.labelsize' : 8,\n",
      "          'ytick.labelsize' : 8,"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Fine Tuning\n",
      "\n",
      "With these smaller plot sizes, the default margins are not enough to\n",
      "display the axis labels, so we need to specify large margins. We do this\n",
      "with an explicit call to the \\`axes()\\` function. In this example, we\n",
      "only have one axis. The typeset LaTeX document will have whitespace on\n",
      "either side of the figure, so we do not need to include this in the\n",
      "figure. Thus, we keep just a bit of whitespace at the top and to the\n",
      "right so that the labels do not extend beyond the bounding box, and add\n",
      "more space to the bottom for the x label:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "#!python numbers=disable\n",
      "pylab.axes([0.125,0.2,0.95-0.125,0.95-0.2])"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### Putting it all Together\n",
      "\n",
      "Here is the python file that generates the plots."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "#!python\n",
      "import pylab\n",
      "from pylab import arange,pi,sin,cos,sqrt\n",
      "fig_width_pt = 246.0  # Get this from LaTeX using \\showthe\\columnwidth\n",
      "inches_per_pt = 1.0/72.27               # Convert pt to inch\n",
      "golden_mean = (sqrt(5)-1.0)/2.0         # Aesthetic ratio\n",
      "fig_width = fig_width_pt*inches_per_pt  # width in inches\n",
      "fig_height = fig_width*golden_mean      # height in inches\n",
      "fig_size =  [fig_width,fig_height]\n",
      "params = {'backend': 'ps',\n",
      "          'axes.labelsize': 10,\n",
      "          'text.fontsize': 10,\n",
      "          'legend.fontsize': 10,\n",
      "          'xtick.labelsize': 8,\n",
      "          'ytick.labelsize': 8,\n",
      "          'text.usetex': True,\n",
      "          'figure.figsize': fig_size}\n",
      "pylab.rcParams.update(params)\n",
      "# Generate data\n",
      "x = pylab.arange(-2*pi,2*pi,0.01)\n",
      "y1 = sin(x)\n",
      "y2 = cos(x)\n",
      "# Plot data\n",
      "pylab.figure(1)\n",
      "pylab.clf()\n",
      "pylab.axes([0.125,0.2,0.95-0.125,0.95-0.2])\n",
      "pylab.plot(x,y1,'g:',label='$\\sin(x)$')\n",
      "pylab.plot(x,y2,'-b',label='$\\cos(x)$')\n",
      "pylab.xlabel('$x$ (radians)')\n",
      "pylab.ylabel('$y$')\n",
      "pylab.legend()\n",
      "pylab.savefig('fig1.eps')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "![](files/attachments/Matplotlib_LaTeX_Examples/fig.png)\n",
      "\n",
      "### producing gray scale dashed plots\n",
      "\n",
      "`An\u00a0obvious\u00a0solution\u00a0is\u00a0to\u00a0greyscale\u00a0convert\u00a0your\u00a0figure,\u00a0but\u00a0for\u00a0readibility,\u00a0adding\u00a0dashes\u00a0is\u00a0often\u00a0better..\u00a0This\u00a0maybe\u00a0implemented\u00a0for\u00a0an\u00a0example\u00a0of\u00a0a\u00a0SigmoidalFunctions\u00a0with\u00a0`\n",
      "![](files/attachments/Matplotlib_LaTeX_Examples_attachments/naka-rushton.png) ![](files/Matplotlib_LaTeX_Examples/naka-rushton.png)\n",
      "\n",
      "### LaTeX using psfrag\n",
      "\n",
      "**Note: This section is obsolete.** Recent versions matplotlib break the\n",
      "psfrag functionality (see for example [this\n",
      "discussion](http://article.gmane.org/gmane.comp.python.matplotlib.general/26740/).\n",
      "That being said, one can use the usetex feature to render the LaTeX text\n",
      "directly with very good results (if you are careful about choosing\n",
      "fonts). I will try to discuss this here further in the near future. --\n",
      "MichaelMcNeilForbes\n",
      "\n",
      "To ensure that your graphics use exactly the same fonts as your\n",
      "document, you can have LaTeX generate and substitute the text for your\n",
      "graph using the psfrag package. This is a good option if you have\n",
      "problems with the \\`text.usetex\\` method (for example, if the\n",
      "appropriate fonts cannot be found.)\n",
      "\n",
      "To do this, simply use plain text for the labels and then replace them\n",
      "using the psfrag package. Here are the modified files to make use of\n",
      "this method:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "\\documentclass[prl,10pt,twocolumn]{revtex4}\n",
      "\\usepackage{graphicx}    % Used to import the graphics\n",
      "\\usepackage{psfrag}\n",
      "\\begin{document}\n",
      "%...\n",
      "\\begin{figure}[t]\n",
      "  \\begin{center}\n",
      "    \\psfrag{sin(x)}{$\\sin(x)$}\n",
      "    \\psfrag{cos(x)}{$\\cos(x)$}\n",
      "    \\psfrag{x (radians)}{$x$ (radians)}\n",
      "    \\psfrag{y}{$y$}\n",
      "    {\\footnotesize                  % Replace tick-lables with smaller font.\n",
      "      \\psfrag{1.0}{1.0}\n",
      "      \\psfrag{0.5}{0.5}\n",
      "      \\psfrag{0.0}{0.0}\n",
      "      \\psfrag{-0.5}{-0.5}\n",
      "      \\psfrag{-1.0}{-1.0}\n",
      "      \\psfrag{-8}{-8}\n",
      "      \\psfrag{-6}{-6}\n",
      "      \\psfrag{-4}{-4}\n",
      "      \\psfrag{-2}{-2}\n",
      "      \\psfrag{0}{0}\n",
      "      \\psfrag{2}{2}\n",
      "      \\psfrag{4}{4}\n",
      "      \\psfrag{6}{6}\n",
      "      \\psfrag{8}{8}\n",
      "      \\showthe\\columnwidth % Use this to determine the width of the figure.\n",
      "      \\includegraphics[width=\\columnwidth]{fig2.eps}\n",
      "    } % Note that the psfrag commands only work in the top-most environment.\n",
      "    \\caption{\\label{fig:sin_cos} Plot of the sine and cosine functions.}\n",
      "  \\end{center}\n",
      "\\end{figure}\n",
      "%...\n",
      "\\end{document}"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "#!python\n",
      "import pylab\n",
      "from pylab import arange,pi,sin,cos,sqrt\n",
      "fig_width_pt = 246.0  # Get this from LaTeX using \\showthe\\columnwidth\n",
      "inches_per_pt = 1.0/72.27               # Convert pt to inch\n",
      "golden_mean = (sqrt(5)-1.0)/2.0         # Aesthetic ratio\n",
      "fig_width = fig_width_pt*inches_per_pt  # width in inches\n",
      "fig_height = fig_width*golden_mean      # height in inches\n",
      "fig_size =  [fig_width,fig_height]\n",
      "params = {'backend': 'ps',\n",
      "          'axes.labelsize': 10,\n",
      "          'text.fontsize': 10,\n",
      "          'legend.fontsize': 10,\n",
      "          'xtick.labelsize': 8,\n",
      "          'ytick.labelsize': 8,\n",
      "          'text.usetex': False,\n",
      "          'figure.figsize': fig_size}\n",
      "pylab.rcParams.update(params)\n",
      "# Generate data\n",
      "x = pylab.arange(-2*pi,2*pi,0.01)\n",
      "y1 = sin(x)\n",
      "y2 = cos(x)\n",
      "# Plot data\n",
      "# Plot data\n",
      "pylab.figure(1)\n",
      "pylab.clf()\n",
      "pylab.axes([0.125,0.2,0.95-0.125,0.95-0.2])\n",
      "pylab.plot(x,y1,'g:',label='sin(x)')\n",
      "pylab.plot(x,y2,'-b',label='cos(x)')\n",
      "pylab.xlabel('x (radians)')\n",
      "pylab.ylabel('y')\n",
      "pylab.legend()\n",
      "pylab.savefig('fig2.eps')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "![](files/attachments/Matplotlib_LaTeX_Examples/psfrag_example.png)\n",
      "\n",
      "### Odds and Ends\n",
      "\n",
      "Another way to set the legend fonts after the legend has been drawn is\n",
      "to use, for example:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "from matplotlib.font_manager import fontManager, FontProperties\n",
      "font= FontProperties(size='x-small');\n",
      "pylab.legend(loc=0, prop=font);"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "-- DavidDonovan\n",
      "\n",
      "### PDF File Size\n",
      "\n",
      "If you have very complex images such as high-resolution contour plots or\n",
      "three-dimensional plots, saving these to vector graphic formats like PDF\n",
      "or EPS can result in unacceptably large files (though with the ability\n",
      "for stunning zooms). One solution is to selectively convert parts of the\n",
      "plot (not the text labels) to a rasterized image. This can be done with\n",
      "the so-called \"mixed-mode rendering\" capability in recent versions of\n",
      "matplotlib. Here is an example as it should probably work:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "#!python\n",
      "from pylab import meshgrid, sin, cos, linspace, contourf, savefig, clf\n",
      "x, y = meshgrid(*(linspace(-1,1,500),)*2)\n",
      "z = sin(20*x**2)*cos(30*y)\n",
      "c = contourf(x,y,z,50)\n",
      "savefig('full_vector.pdf')\n",
      "clf()\n",
      "c = contourf(x,y,z,50,rasterized=True)\n",
      "savefig('rasterized.pdf')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "however, {{{contourf}}} currently does not support the {{{rasterized}}} option (which is silently ignored).  Some other plot elements do however.  I am looking into a solution for this.  -- MichaelMcNeilForbes"
     ]
    }
   ],
   "metadata": {}
  }
 ]
}